package com.snc.controller.app;


import com.snc.entity.DynamicCodeFormMap;
import com.snc.entity.ResUserFormMap;
import com.snc.entity.ResidentFormMap;
import com.snc.entity.UserFormMap;
import com.snc.exception.BusinessException;
import com.snc.plugin.Result;
import com.snc.util.DynamicCodeUtils;
import com.snc.util.NetworkUtil;
import com.snc.util.SmsApi;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP-用户注册，登陆，找回密码等使用的发送动态验证码
 */
@Controller
@RequestMapping("/app/code")
public class DynamicCodeController{

	/**
	 * 发送记录
	 * key : 当前请求IP地址
	 * value : 上次发送时间
	 */
	private Map<String,Double> sendRecords = new HashMap<>();

	/**
	 * 发送短线验证码（注册时使用，需要判断系统是否存在该用户）
	 * @param phone 手机号码
	 * @return 结果
	 */
	@ResponseBody
	@Transactional(readOnly=false)
	@RequestMapping(method = RequestMethod.POST,value = "reg/send")
	public Result sendWithReg(HttpServletRequest request,String phone) throws Exception {
		this.validSend(request);
		ResidentFormMap resident = new ResidentFormMap();

		//查询该手机号码是否已注册
		List<ResidentFormMap> results = resident.findByAttribute("phone",phone);
		if(results != null && results.size() > 0){
			throw new BusinessException("该手机号码已注册，请直接登录");
		}

		return this.send(phone);
	}

	/**
	 * 发送短线验证码（找回密码使用，需要判断系统是否存在该用户）
	 * @param phone 手机号码
	 * @return 结果
	 */
	@ResponseBody
	@Transactional(readOnly=false)
	@RequestMapping(method = RequestMethod.POST,value = "find/send")
	public Result sendWithFind(HttpServletRequest request,String phone) throws Exception {
		this.validSend(request);
		ResidentFormMap resident = new ResidentFormMap();

		//查询该手机号码是否已注册
		List<ResidentFormMap> results = resident.findByAttribute("phone",phone);
		if(results == null || results.size() == 0){
			throw new BusinessException("该手机号码还未注册");
		}
		this.send(phone);

		return Result.Success(results.get(0).get("id"));
	}

	/**
	 * 发送短线验证码
	 * @param phone 手机号码
     * @return 结果
     */
	@ResponseBody
	@Transactional(readOnly=false)
	@RequestMapping(method = RequestMethod.POST,value = "common/send")
	public Result sendCommon(HttpServletRequest request,String phone) throws Exception {
		this.validSend(request);
		return this.send(phone);
	}

	/**
	 * 验证是否合法发送
	 * @param request 请求
     */
	private void validSend(HttpServletRequest request){
//		String ip = NetworkUtil.getIpAddress(request);
//		//获取当前IP上一次发送记录
//		Double prev = this.sendRecords.get(ip);
//		double now = new Date().getTime();
//		if(prev != null && now - prev < 50 * 1000){
//			throw  new BusinessException("短信发送时间间隔太短，请稍后发送");
//		}
//		this.sendRecords.put(ip,now);
	}

	/**
	 * 通过的短信发送
	 * @param phone
	 * @return
	 * @throws Exception
     */
	private Result send(String phone) throws Exception {

		//如果手机号码包含 +，那么不支持
		if(phone.indexOf("+") != -1){
			throw  new BusinessException("不支持该手机号码");
		}

		//生成随机码
		String code = "8888";
		DynamicCodeFormMap entity = new DynamicCodeFormMap();
		entity.put("phone",phone);
		entity.put("code",code);
		entity.put("createTime",new Date());

		entity.save();
		System.out.println(code);

		return Result.Success("短信发送成功，请注意查收");
	}

	/**
	 * 验证短信验证码
	 * @param phone 手机号码
	 * @return
	 */
	@ResponseBody
	@RequestMapping(method = RequestMethod.POST,value = "valid")
	public Result valid(String phone,String code){
		DynamicCodeFormMap entity = new DynamicCodeFormMap();
		entity.put("phone",phone);
		entity.put("code",code);
		entity = entity.findbyFrist();
		if(entity == null){
			throw new BusinessException("验证码错误");
		}

		Date now = new Date();
		Date old = entity.getDate("createTime");
//		if(now.getTime() - old.getTime() > 1000 * 60 * 30){
//			throw new BusinessException("验证码已失效，请重新发送");
//		}

		return Result.Null();
	}


}